/**
   Copyright 2011 Фроловский А. В.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   This file is a part of MyStats project
 */

package foo.mystats;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import foo.mystats.contentprovider.RowContentProvider;
import foo.mystats.db.RowTable;

public class RowListActivity extends ActionBarActivity implements OnClickListener,
    LoaderManager.LoaderCallbacks<Cursor> {
  private AlertDialog deleteConfirmAlert;
  private ListView lv;

  private SimpleCursorAdapter adapter;

  private long selectedRowId;
  private String selectedRowName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.row_list);

    lv = (ListView) findViewById(R.id.rowlist_listview);
    lv.setOnItemClickListener(onClickListener);
    registerForContextMenu(lv);

    fillData();
  }

  private void fillData() {
    String[] from = new String[] {
        RowTable.COLUMN_NAME,
        RowTable.COLUMN_DESCRIPTION,
        BaseColumns._ID
    };

    int[] to = new int[] {
        R.id.row_name,
        R.id.row_description
    };

    adapter = new SimpleCursorAdapter(this, R.layout.row_list_item, null, from, to, 0);
    lv.setAdapter(adapter);

    getSupportLoaderManager().initLoader(0, null, this);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.row_list_options, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.row_list_options_menu_add:
        Intent addRowIntent = new Intent(this, RowEditActivity.class);
        startActivity(addRowIntent);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    getMenuInflater().inflate(R.menu.row_list_context, menu);

    Cursor c = (Cursor) lv.getItemAtPosition(((AdapterContextMenuInfo) menuInfo).position);
    if (c != null) {
      selectedRowId = c.getLong(c.getColumnIndexOrThrow(BaseColumns._ID));
      selectedRowName = c.getString(c.getColumnIndexOrThrow(RowTable.COLUMN_NAME));
      menu.setHeaderTitle(selectedRowName);
    }
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.row_list_context_menu_edit:
        startEditRowActivity();
        return true;
      case R.id.row_list_context_menu_delete:
        showDeleteConfirmationDialog();
        return true;
      case R.id.row_list_context_menu_stats:
        showStatistics();
        return true;
      default:
        return super.onContextItemSelected(item);
    }
  }

  public void startEditRowActivity() {
    Intent editRowIntent = new Intent(this, RowEditActivity.class);
    editRowIntent.putExtra("row_uri", Uri.parse(RowContentProvider.CONTENT_URI + "/" + selectedRowId));
    startActivity(editRowIntent);
  }

  public void showDeleteConfirmationDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setMessage(R.string.msg_row_delete_confirm)
        .setCancelable(false)
        .setPositiveButton(R.string.yes, this)
        .setNegativeButton(R.string.no, this);
    deleteConfirmAlert = builder.create();
    deleteConfirmAlert.show();
  }

  public void showStatistics() {
    Intent statisticsIntent = new Intent(this, StatisticsActivity.class);
    statisticsIntent.putExtra("row_id", selectedRowId);
    statisticsIntent.putExtra("row_name", selectedRowName);
    startActivity(statisticsIntent);
  }

  @Override
  public void onClick(DialogInterface dialog, int which) {
    if (dialog == deleteConfirmAlert) {
      switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
          Uri uri = Uri.parse(RowContentProvider.CONTENT_URI + "/" + selectedRowId);
          getContentResolver().delete(uri, null, null);
          fillData();
          break;
        case DialogInterface.BUTTON_NEGATIVE:
          dialog.dismiss();
          break;
      }
    }
  }

  OnItemClickListener onClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

      Cursor cursor = ((SimpleCursorAdapter) lv.getAdapter()).getCursor();
      cursor.moveToPosition(position);

      Intent dataListIntent = new Intent(RowListActivity.this, DataListActivity.class);

      dataListIntent.putExtra(DataListActivity.PARAM_ROW_ID,
          cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID)));
      dataListIntent.putExtra(DataListActivity.PARAM_ROW_NAME,
          cursor.getString(cursor.getColumnIndexOrThrow(RowTable.COLUMN_NAME)));
      dataListIntent.putExtra(DataListActivity.PARAM_ROW_DATA_TYPE,
          cursor.getInt(cursor.getColumnIndexOrThrow(RowTable.COLUMN_DATA_TYPE)));
      dataListIntent.putExtra(DataListActivity.PARAM_ROW_IS_TIME_NEEDED,
          cursor.getInt(cursor.getColumnIndexOrThrow(RowTable.COLUMN_IS_TIME_NEEDED)) == 1);
      startActivity(dataListIntent);
    }
  };

  @Override
  public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection = {
        RowTable.COLUMN_ID + " AS " + BaseColumns._ID,
        RowTable.COLUMN_NAME,
        RowTable.COLUMN_DESCRIPTION,
        RowTable.COLUMN_DATA_TYPE,
        RowTable.COLUMN_IS_TIME_NEEDED,
    };

    String sortOrder = RowTable.COLUMN_NAME + " ASC";

    return new CursorLoader(this, RowContentProvider.CONTENT_URI, projection, null, null, sortOrder);
  }

  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    adapter.swapCursor(cursor);
  }

  @Override
  public void onLoaderReset(Loader<Cursor> loader) {
    adapter.swapCursor(null);
  }
}
